package com.glsc.ngateway.shortmsg.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.glsc.ngateway.common.base.domain.mysql.gateway.shortmsg.NoticeMessageSend;
import com.glsc.ngateway.common.api.shortmsg.utils.SendStatus;
import com.glsc.ngateway.common.base.repo.mysql.gateway.shortmsg.NoticeMessageSendRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

public class SendMsgTask implements Runnable {

    Logger logger = LoggerFactory.getLogger(SendMsgTask.class);

    NoticeMessageSendRepository noticeMessageSendRepository;

    RestTemplate restTemplate;

    String url;

    ObjectMapper mapper = new ObjectMapper();

    public SendMsgTask(NoticeMessageSendRepository noticeMessageSendRepository, RestTemplate restTemplate, String url) {
        this.noticeMessageSendRepository = noticeMessageSendRepository;
        this.restTemplate = restTemplate;
        this.url = url;
    }

    @Override
    public void run() {
        logger.debug("send shortmsg task start...");
        List<NoticeMessageSend> dbrecs = noticeMessageSendRepository.findBySendStatus(SendStatus.RECIEVED.getCode());
        dbrecs.forEach(r -> {
            try {
                Map<String, Object> request = ShortMessageSupport.getShortMessageParam(r.getContent(), r.getOpState(), r.getTelephone(), r.getSysid());
                logger.info("向短信平台发送消息:{}", request);
                String response = restTemplate.postForObject(url, request, String.class);
                logger.info("从短信平台接收到结果:{}", response);
                r.setRescontent(response);
                r.setSendStatus(SendStatus.SEND_FAIL.getCode());
                Map resMap = mapper.readValue(response, Map.class);
                if (resMap.containsKey("code") && ("20000".equals(resMap.get("code").toString()))) {
                    try {
                        if (resMap.containsKey("data")) {
                            if (((Map) resMap.get("data")).containsKey("datasets")) {
                                if (((Map) (((Map) resMap.get("data")).get("datasets"))).containsKey("dataset0")) {
                                    Map dataset0 = (Map) ((List) ((Map) (((Map) resMap.get("data")).get("datasets"))).get("dataset0")).get(0);
                                    if (dataset0.containsKey("error_no") && ("0".equals(dataset0.get("error_no").toString()))) {
                                        r.setSendStatus(SendStatus.SEND_SUCCESS.getCode());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        logger.error("短信平台解析成功标志位失败:", e);
                    }
                }
            } catch (Exception e) {
                logger.error("短信平台报文解析失败", e);
            } finally {
                noticeMessageSendRepository.save(r);
            }
        });

        logger.debug("send shortmsg task end...");
    }
}
